<template>
  <div class="mc-root">
    <!-- 顶部栏，简化为类似微信标题栏 -->
    <header class="mc-header">
      <div class="mc-header-left">
        <span class="mc-header-title">消息中心</span>
      </div>
      <div class="mc-header-right">
        <button class="mc-header-btn" @click="refreshConversations">刷新</button>
        <button class="mc-header-btn" @click="$router.back()">返回</button>
      </div>
    </header>

    <main class="mc-main">
      <!-- 左侧：会话列表 -->
      <aside class="mc-sidebar">
        <div class="mc-sidebar-search">
          <input
            type="text"
            placeholder="搜索会话或订单..."
            class="mc-sidebar-search-input"
          />
        </div>
        <div class="mc-conv-list">
          <button
            v-for="c in conversations"
            :key="c.id"
            @click="openConversation(c)"
            class="mc-conv-item"
            :class="{ 'mc-conv-item-active': current && current.id === c.id }"
          >
            <div class="mc-conv-avatar">
              {{ c.pickup_code ? '单' : ((c.other_nickname || '').charAt(0) || '聊') }}
            </div>
            <div class="mc-conv-main">
              <div class="mc-conv-row-top">
                <div class="mc-conv-title">
                  {{ c.pickup_code
                     ? `取件码：${c.pickup_code}`
                     : (c.other_nickname || (c.order_id ? `订单 #${c.order_id}` : `会话 #${c.id}`))
                  }}
                </div>
                <div class="mc-conv-time">{{ (c.updated_at || '').replace('T',' ').slice(0,16) }}</div>
              </div>
              <div class="mc-conv-row-bottom">
                <div class="mc-conv-last" v-if="c.last_message">
                  {{ (c.last_message.content || '') }}
                </div>
                <span v-if="c.unread_count > 0" class="mc-conv-unread">{{ c.unread_count }}</span>
              </div>
            </div>
          </button>
          <div v-if="!conversations.length" class="mc-conv-empty">暂无会话</div>
        </div>
      </aside>

      <!-- 右侧：聊天区域 -->
      <section class="mc-chat">
        <!-- 聊天顶部 -->
        <div class="mc-chat-header">
          <div class="mc-chat-title">
            {{ current
               ? (current.pickup_code
                   ? `取件码：${current.pickup_code}`
                   : (current.other_nickname || (current.order_id ? `订单 #${current.order_id}` : `会话 #${current.id}`)))
               : '请选择左侧会话开始聊天'
            }}
          </div>
          <button v-if="current" class="mc-chat-header-btn" @click="loadMessages(current.id)">刷新消息</button>
        </div>

        <!-- 聊天消息区 -->
        <div ref="messagesContainer" class="mc-chat-body">
          <div v-if="!current" class="mc-chat-placeholder">从左侧选择一个会话</div>
          <div v-else-if="messages.length === 0" class="mc-chat-placeholder">暂无消息，开始对话吧</div>
          <div v-else class="mc-chat-messages">
            <template v-for="(m, idx) in messages" :key="m.id">
              <!-- 时间分割，类似微信：间隔较大时居中显示一次 -->
              <div
                v-if="idx === 0 || (new Date(messages[idx].created_at) - new Date(messages[idx-1].created_at) > 5 * 60 * 1000)"
                class="mc-msg-time-divider"
              >
                {{ formatTime(m.created_at) }}
              </div>

              <!-- 消息行 -->
              <div
                class="mc-msg-row"
                :class="Number(m.sender_id) === Number(userId) ? 'mc-msg-row-self' : 'mc-msg-row-other'"
              >
                <!-- 对方在左：头像在最左，气泡在右；自己在右：气泡在左，头像在最右 -->
                <div
                  v-if="Number(m.sender_id) !== Number(userId)"
                  class="mc-msg-avatar mc-msg-avatar-other"
                >
                  TA
                </div>
                <div class="mc-msg-bubble-wrap">
                  <div
                    class="mc-msg-bubble"
                    :class="Number(m.sender_id) === Number(userId) ? 'mc-msg-bubble-self' : 'mc-msg-bubble-other'"
                  >
                    <div class="mc-msg-text">{{ m.content }}</div>
                  </div>
                </div>
                <div
                  v-if="Number(m.sender_id) === Number(userId)"
                  class="mc-msg-avatar mc-msg-avatar-self"
                >
                  我
                </div>
              </div>
            </template>
          </div>
        </div>

        <!-- 底部输入区 -->
        <div class="mc-chat-footer">
          <!-- 工具栏：表情面板（简化版） -->
          <div class="mc-chat-toolbar">
            <button
              type="button"
              class="mc-chat-tool-btn"
              @click="toggleEmojiPanel"
              :disabled="!current"
            >
              😊 表情
            </button>
            <div v-if="current && showEmojiPanel" class="mc-emoji-panel">
              <button
                v-for="e in emojiList"
                :key="e"
                type="button"
                class="mc-emoji-btn"
                @click="appendEmoji(e)"
              >{{ e }}</button>
            </div>
          </div>
          <div class="mc-chat-input-wrap" :class="{ 'mc-chat-input-disabled': !current }">
            <textarea
              v-model="draft"
              class="mc-chat-input"
              placeholder="输入消息，按 Enter 发送"
              :disabled="!current"
              @keyup.enter.prevent="send"
            ></textarea>
          </div>
          <div class="mc-chat-footer-actions">
            <span class="mc-chat-tip">当前账号：{{ userId || '未登录' }}</span>
            <button
              class="mc-chat-send-btn"
              @click="send"
              :disabled="!current || !draft.trim()"
            >发送</button>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'MessageCenter',
  data() {
    const stored = localStorage.getItem('userId')
    return {
      userId: stored ? Number(stored) : 0,
      conversations: [],
      current: null,
      messages: [],
      draft: '',
      pollTimer: null,
      showEmojiPanel: false,
      emojiList: ['😀','😂','🤣','😊','😍','😅','😢','😡','👍','🙏']
    }
  },
  methods: {
    formatTime(timeStr) {
      if (!timeStr) return ''
      // 兼容后端可能返回的多种时间格式（含/不含 T 和时区）
      let dt
      try {
        dt = new Date(timeStr)
        if (Number.isNaN(dt.getTime())) {
          dt = new Date(timeStr.replace('T', ' ').slice(0, 19))
        }
      } catch (e) {
        dt = new Date(timeStr.replace('T', ' ').slice(0, 19))
      }
      const now = new Date()
      const diff = now - dt
      const minutes = Math.floor(diff / 60000)
      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      const hours = Math.floor(minutes / 60)
      if (hours < 24) return `${hours}小时前`
      const days = Math.floor(hours / 24)
      if (days < 7) return `${days}天前`
      return dt.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
    },
    async refreshConversations() {
      if (!this.userId) { this.$router.push('/login'); return }
      const { data } = await axios.get(`/api/messages/conversations`, { params: { userId: this.userId } })
      const rows = (data && (data.data || data)) || []
      // 后端 last_message 是 JSON_OBJECT，某些情况下会是字符串，做兼容解析
      this.conversations = rows.map(r => ({
        ...r,
        last_message: (typeof r.last_message === 'string') ? (JSON.parse(r.last_message || '{}')) : r.last_message,
        // 如果当前会话正在打开，则前端直接将未读数视为0，保证红点在阅读后消失
        unread_count: this.current && Number(this.current.id) === Number(r.id) ? 0 : (r.unread_count || 0)
      }))
    },
    startPolling() {
      if (this.pollTimer) return
      this.pollTimer = setInterval(() => {
        // 只刷新会话列表，不打断当前会话
        this.refreshConversations()
      }, 5000)
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
    },
    async openConversation(c) {
      this.current = c
      // 前端立即把该会话的未读数清零，保证红点在点击后消失
      this.conversations = this.conversations.map(item =>
        Number(item.id) === Number(c.id)
          ? { ...item, unread_count: 0 }
          : item
      )
      await this.loadMessages(c.id)
      // 标记已读（用最后一条消息）
      if (this.messages.length) {
        const lastId = this.messages[this.messages.length - 1].id
        await axios.post(`/api/messages/${c.id}/read`, { user_id: this.userId, last_message_id: lastId })
        await this.refreshConversations()
      }
    },
    async loadMessages(cid) {
      const { data } = await axios.get(`/api/messages/${cid}`, { params: { page: 1, size: 50 } })
      this.messages = (data && (data.data || data)) || []
      this.$nextTick(() => {
        if (this.$refs.messagesContainer) {
          this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight
        }
      })
    },
    async send() {
      if (!this.current || !this.draft.trim()) return
      const content = this.draft
      this.draft = ''
      try {
        await axios.post(`/api/messages/${this.current.id}/send`, {
          sender_id: this.userId,
          content
        })
        await this.loadMessages(this.current.id)
        await this.refreshConversations()
        // 确保滚动到底部
        this.$nextTick(() => {
          if (this.$refs.messagesContainer) {
            this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight
          }
        })
      } catch (e) {
        console.error('发送消息失败', e)
        alert('发送失败，请稍后再试')
        this.draft = content // 恢复输入
      }
    },
    toggleEmojiPanel() {
      if (!this.current) return
      this.showEmojiPanel = !this.showEmojiPanel
    },
    appendEmoji(e) {
      if (!this.current) return
      const emoji = e || '😀'
      this.draft = (this.draft || '') + emoji
    },
    async ensureOpenFromQuery() {
      const cid = Number(this.$route.query.cid)
      if (cid) {
        await this.refreshConversations()
        const match = this.conversations.find(c => Number(c.id) === cid)
        if (match) await this.openConversation(match)
      } else {
        await this.refreshConversations()
      }
    }
  },
  async mounted() {
    if (!this.userId) { this.$router.push('/login'); return }
    await this.ensureOpenFromQuery()
    this.startPolling()
  },
  beforeDestroy() {
    this.stopPolling()
  }
}
</script>

<style scoped>
.mc-root {
  background-color: #f3f4f6;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
.mc-chat-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}
.mc-chat-tool-btn {
  font-size: 13px;
  padding: 4px 10px;
  border-radius: 6px;
  border: none;
  background-color: #f3f4f6;
  color: #4b5563;
  cursor: pointer;
}
.mc-chat-tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.mc-chat-tool-btn:not(:disabled):hover {
  background-color: #e5e7eb;
}
.mc-emoji-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-left: 8px;
}
.mc-emoji-btn {
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 18px;
  line-height: 1;
}
.mc-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 48px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #ffffff;
  box-shadow: 0 1px 2px rgba(15,23,42,0.05);
}
.mc-header-left { display: flex; align-items: center; gap: 8px; }
.mc-header-title { font-size: 14px; font-weight: 600; color: #111827; }
.mc-header-right { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.mc-header-btn {
  padding: 4px 8px;
  border-radius: 4px;
  border: none;
  background: transparent;
  color: #4b5563;
  cursor: pointer;
}
.mc-header-btn:hover { background-color: #f3f4f6; }

.mc-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.mc-sidebar {
  width: 280px;
  background-color: #f9fafb;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
}
.mc-sidebar-search {
  padding: 8px 12px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #f9fafb;
}
.mc-sidebar-search-input {
  width: 100%;
  font-size: 12px;
  padding: 6px 8px;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  background-color: #ffffff;
  outline: none;
}
.mc-sidebar-search-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 1px rgba(59,130,246,0.25);
}
.mc-conv-list {
  flex: 1;
  overflow-y: auto;
}
.mc-conv-item {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  font-size: 13px;
  color: #111827;
  text-align: left;
  border: none;
  background: transparent;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
}
.mc-conv-item:hover { background-color: #f3f4f6; }
.mc-conv-item-active { background-color: #eff6ff; }
.mc-conv-avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background-color: #3b82f6;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  margin-right: 12px;
  flex-shrink: 0;
}
.mc-conv-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}
.mc-conv-row-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2px;
}
.mc-conv-title {
  font-size: 13px;
  font-weight: 500;
  color: #111827;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 160px;
}
.mc-conv-time {
  font-size: 11px;
  color: #9ca3af;
  margin-left: 8px;
  white-space: nowrap;
}
.mc-conv-row-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.mc-conv-last {
  font-size: 12px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}
.mc-conv-unread {
  font-size: 10px;
  background-color: #ef4444;
  color: #ffffff;
  padding: 2px 6px;
  border-radius: 999px;
  margin-left: 8px;
}
.mc-conv-empty {
  font-size: 12px;
  color: #9ca3af;
  text-align: center;
  padding: 24px 0;
}

.mc-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f3f4f6;
}
.mc-chat-header {
  height: 48px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e5e7eb;
  background-color: #ffffff;
}
.mc-chat-title {
  font-size: 14px;
  font-weight: 500;
  color: #111827;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.mc-chat-header-btn {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  border: none;
  background: transparent;
  color: #4b5563;
  cursor: pointer;
}
.mc-chat-header-btn:hover { background-color: #f3f4f6; }

.mc-chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px 24px;
  background-color: #f3f4f6;
}
.mc-chat-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  color: #9ca3af;
}
.mc-chat-messages { display: flex; flex-direction: column; gap: 12px; }

.mc-msg-time-divider {
  align-self: center;
  padding: 2px 8px;
  margin: 4px 0 8px;
  border-radius: 8px;
  background-color: #e5e7eb;
  font-size: 11px;
  color: #4b5563;
}

.mc-msg-row {
  display: flex;
  align-items: flex-end;
  gap: 8px;
}
.mc-msg-row-self {
  flex-direction: row;
  justify-content: flex-end; /* 整行靠右，顺序为：气泡 在左，头像 在右 */
}
.mc-msg-row-other {
  flex-direction: row;
  justify-content: flex-start;
}
.mc-msg-avatar {
  width: 32px;
  height: 32px;
  border-radius: 999px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 600;
  box-shadow: 0 1px 2px rgba(15,23,42,0.15);
}
.mc-msg-avatar-self { background-color: #22c55e; color: #ffffff; }
.mc-msg-avatar-other { background-color: #e5e7eb; color: #374151; }
.mc-msg-bubble-wrap {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}
.mc-msg-bubble {
  padding: 8px 12px;
  border-radius: 14px;
  font-size: 13px;
  line-height: 1.5;
  box-shadow: 0 1px 2px rgba(15,23,42,0.08);
}
.mc-msg-bubble-self {
  background-color: #22c55e;
  color: #ffffff;
  border-bottom-right-radius: 4px;
}
.mc-msg-bubble-other {
  background-color: #ffffff;
  color: #111827;
  border: 1px solid #e5e7eb;
  border-bottom-left-radius: 4px;
}
.mc-msg-text {
  white-space: pre-wrap;
  word-break: break-word;
}
.mc-msg-time {
  margin-top: 2px;
  font-size: 11px;
  color: #9ca3af;
  padding: 0 2px;
}

.mc-chat-footer {
  border-top: 1px solid #e5e7eb;
  background-color: #ffffff;
  padding: 8px 16px 12px;
  display: flex;
  flex-direction: column;
}
.mc-chat-input-wrap {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background-color: #ffffff;
  margin-bottom: 8px;
}
.mc-chat-input-disabled { opacity: 0.6; }
.mc-chat-input {
  width: 100%;
  resize: none;
  font-size: 13px;
  padding: 8px 10px;
  border: none;
  outline: none;
  background: transparent;
  height: 64px;
}
.mc-chat-footer-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.mc-chat-tip {
  font-size: 11px;
  color: #9ca3af;
}
.mc-chat-send-btn {
  padding: 6px 16px;
  font-size: 13px;
  border-radius: 6px;
  border: none;
  background-color: #22c55e;
  color: #ffffff;
  cursor: pointer;
}
.mc-chat-send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.mc-chat-send-btn:not(:disabled):hover {
  background-color: #16a34a;
}
</style>
